package com.yeskery.nut.http;

import com.yeskery.nut.application.NutApplication;
import com.yeskery.nut.bind.HttpResponseBodyMetadata;
import com.yeskery.nut.bind.TextableHttpResponseBodyHandler;
import com.yeskery.nut.core.MediaType;
import com.yeskery.nut.core.NutException;
import com.yeskery.nut.extend.responsive.DefaultResponsive;
import com.yeskery.nut.extend.responsive.JsonResponsive;
import com.yeskery.nut.extend.responsive.JsonResponsivePlugin;
import com.yeskery.nut.extend.responsive.Responsive;

/**
 * application/json响应体处理器
 * @author YESKERY
 * 2024/9/23
 */
public class ApplicationJsonHttpResponseBodyHandler implements TextableHttpResponseBodyHandler {

    @Override
    public void handle(HttpResponseBodyMetadata metadata) {
        if (!metadata.getApplicationContext().getBean(NutApplication.class).getNutWebConfigure().getPluginManager().containPlugin(JsonResponsivePlugin.class)) {
            throw new NutException("Use HttpResponseBodyHandler[ApplicationJsonHttpResponseBodyHandler], But Unable Find Plugin[" + JsonResponsivePlugin.class + "]");
        }
        Responsive responsive = metadata.getBindContext().getObject(JsonResponsive.class);
        responsive.writeBody(metadata.getResult());
    }

    @Override
    public MediaType[] supportMediaTypes() {
        return new MediaType[]{MediaType.APPLICATION_JSON};
    }

    @Override
    public String getExtractText(HttpResponseBodyMetadata metadata) {
        if (!metadata.getApplicationContext().getBean(NutApplication.class).getNutWebConfigure().getPluginManager().containPlugin(JsonResponsivePlugin.class)) {
            throw new NutException("Use HttpResponseBodyHandler[ApplicationJsonHttpResponseBodyHandler], But Unable Find Plugin[" + JsonResponsivePlugin.class + "]");
        }
        DefaultResponsive responsive = metadata.getBindContext().getObject(JsonResponsive.class);
        return responsive.getResponsiveConvert().convertTo(metadata.getResult());
    }
}
